﻿using OpenAI.GPT3;
using OpenAI.GPT3.Managers;
using OpenAI.GPT3.ObjectModels;
using OpenAI.GPT3.ObjectModels.RequestModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ChatGPT
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public ObservableCollection<Message> Messages { set; get; } = new ObservableCollection<Message>();
        const string OPENAPI_TOKEN = "sk-";
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnMinSize_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void btnCloseApp_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button? btn = sender as Button;
            if (btn != null)
            {
                var parent = VisualTreeHelper.GetParent(btn);
                while (!(parent is TextBox))
                {
                    parent = VisualTreeHelper.GetParent(parent);
                }
                TextBox txt = parent as TextBox;
                if (txt != null)
                {
                    txt.Clear();
                }
            }

        }

        private async void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtBoxPromot.Text)) return;
            Message message = new Message() { IsSend = true ,Msg = txtBoxPromot.Text };
            Messages.Add(message);
            txtBoxPromot.Clear();
            await Chat(message.Msg);
            
            txtBoxPromot.IsEnabled = true;
        }

        private async Task Chat(string prompt)
        {
            Messages.Add(new Message() { IsSend=false,Msg = "思考中..." });
            OpenAIService service = new OpenAIService(new OpenAiOptions() { ApiKey = OPENAPI_TOKEN });
            CompletionCreateRequest createRequest = new CompletionCreateRequest()
            {

                Prompt = prompt,
                Temperature = (float)temperature.Value,
                MaxTokens = (int)max_tokens.Value,
                TopP = (float)top_n.Value
            };
            if (!string.IsNullOrWhiteSpace(txtBoxStop.Text.Trim()))
            {
                createRequest.Stop = txtBoxStop.Text.Trim();
            }
            var res = await service.Completions.CreateCompletion(createRequest, Models.TextDavinciV3);
            txtBoxPromot.IsEnabled = false;
            if (res.Successful)
            {
                var answer = res.Choices.FirstOrDefault().Text.TrimStart();
                Message message = new Message() { IsSend=false, Msg = answer };
                Messages.Remove(Messages.Last());
                Messages.Add(message);
            }
            else
            {
                Message message = new Message() { IsSend = false, Msg = "不知道为什么，我回答不了这个问题" };
                Messages.Remove(Messages.Last());
                Messages.Add(message);
            }

        }

        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            TextBlock_MouseDown(null, null);
        }
    }
}
